import requests
from flask import Flask, render_template_string, request, jsonify
import json
import uuid
import urllib3
from requests.exceptions import ChunkedEncodingError

urllib3.disable_warnings()

app = Flask(__name__)

# 存储对话历史
conversations = {}

# TOKEN 文件路径
TOKEN_FILE_PATH = "token.txt"

def read_token_from_file():
    """
    从文件中读取 TOKEN
    """
    try:
        with open(TOKEN_FILE_PATH, "r") as file:
            token = file.read().strip()
        return token
    except Exception as e:
        print(f"读取 TOKEN 文件时发生错误: {e}")
        return None


# 调用Agent的函数
def call_agent(query, conversation_id=None):
    # 华为云 AI Agent API 端点
    # 注意：需要替换为正确的 API 端点 URL
    url = f"YOUR_URL"

    payload = json.dumps({"query": query}, ensure_ascii=False)

    # 获取 TOKEN
    token = read_token_from_file()
    if not token:
        print("TOKEN 无法加载，检测失败")
        return "抱歉，系统配置错误，无法连接到AI服务。"

    headers = {
        'Content-Type': 'application/json',
        'X-Auth-Token': token
    }

    try:
        response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"), verify=False, stream=True)
        response.encoding = 'utf-8'
        print(f"状态码: {response.status_code}")
        
        # 检查响应状态
        if response.status_code != 200:
            print(f"错误响应: {response.text}")
            return f"抱歉，AI服务返回错误（状态码：{response.status_code}）。请检查配置或稍后重试。"

        # 处理流式响应
        full_content = ""
        for line in response.iter_lines(decode_unicode=True):
            if line and line.startswith('data:'):
                data_str = line[len('data:'):].strip()
                if data_str == '[DONE]':
                    break
                try:
                    data_json = json.loads(data_str)
                    content = data_json.get('content', '')
                    if content:
                        full_content += content
                        print(f"接收到内容: {content}")
                except json.JSONDecodeError as e:
                    print(f"JSON解析错误: {e}, 数据: {data_str}")
                    pass
        
        response.close()
        
        if not full_content:
            print("警告: 未接收到任何内容")
            return "抱歉，AI未返回任何响应。请稍后重试。"
        
        return full_content

    except ChunkedEncodingError as e:
        print(f"分块编码错误: {e}")
        return "抱歉，网络传输出现问题，请重试。"
    except Exception as e:
        print(f"请求发生错误: {e}")
        return "抱歉，连接AI服务时发生错误。"


# 主页路由
@app.route('/')
def index():
    return render_template_string('''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI作业评分系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.4.0/css/all.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#7C3AED',
                        secondary: '#10B981',
                        accent: '#F59E0B',
                        neutral: '#F3F4F6',
                        dark: '#1F2937',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .chat-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            }
            .agent-avatar {
                transition: all 0.3s ease;
            }
            .agent-avatar:hover {
                transform: scale(1.05);
            }
            .chat-container {
                transform: translateX(100%);
                transition: transform 0.3s ease-out;
            }
            .chat-container.active {
                transform: translateX(0);
            }
            .message-bubble {
                max-width: 80%;
                animation: fadeIn 0.3s ease-in-out;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(10px); }
                to { opacity: 1; transform: translateY(0); }
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-dark">
    <!-- 主页面内容 -->
    <div class="min-h-screen flex flex-col">
        <!-- 顶部导航栏 -->
        <header class="bg-white shadow-sm">
            <div class="container mx-auto px-4 py-4 flex justify-between items-center">
                <div class="flex items-center space-x-2">
                    <i class="fa fa-graduation-cap text-primary text-2xl"></i>
                    <h1 class="text-xl font-bold text-primary">AI作业评分系统</h1>
                </div>
                <nav class="hidden md:flex space-x-8">
                    <a href="#" class="text-gray-600 hover:text-primary transition-colors">首页</a>
                    <a href="#" class="text-gray-600 hover:text-primary transition-colors">作业管理</a>
                    <a href="#" class="text-gray-600 hover:text-primary transition-colors">成绩查询</a>
                    <a href="#" class="text-gray-600 hover:text-primary transition-colors">帮助中心</a>
                </nav>
                <button class="md:hidden text-gray-600">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </header>

        <!-- 主要内容区 -->
        <main class="flex-grow container mx-auto px-4 py-8">
            <div class="bg-gradient-to-r from-purple-50 to-blue-50 rounded-xl shadow-sm p-8 mb-8">
                <h2 class="text-3xl font-bold mb-4 text-dark">欢迎使用AI作业评分系统</h2>
                <p class="text-gray-700 mb-6 text-lg">智能化作业评分平台，采用先进的AI技术为学生作业提供快速、准确、公正的评分服务。点击右下角的AI助手可以获取帮助和指导。</p>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div class="bg-white rounded-lg p-6 hover:shadow-lg transition-all hover:transform hover:scale-105">
                        <div class="text-primary text-4xl mb-4">
                            <i class="fa fa-upload"></i>
                        </div>
                        <h3 class="font-bold text-lg mb-2">作业提交</h3>
                        <p class="text-gray-600 text-sm">支持多种格式的作业提交，包括文档、代码、图片等，操作简单便捷。</p>
                    </div>

                    <div class="bg-white rounded-lg p-6 hover:shadow-lg transition-all hover:transform hover:scale-105">
                        <div class="text-secondary text-4xl mb-4">
                            <i class="fa fa-magic"></i>
                        </div>
                        <h3 class="font-bold text-lg mb-2">AI智能评分</h3>
                        <p class="text-gray-600 text-sm">采用先进的AI算法，自动评分并提供详细的评价反馈和改进建议。</p>
                    </div>

                    <div class="bg-white rounded-lg p-6 hover:shadow-lg transition-all hover:transform hover:scale-105">
                        <div class="text-accent text-4xl mb-4">
                            <i class="fa fa-chart-bar"></i>
                        </div>
                        <h3 class="font-bold text-lg mb-2">成绩统计</h3>
                        <p class="text-gray-600 text-sm">实时查看成绩统计和分析报告，全面了解学习情况和进步轨迹。</p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-sm p-6">
                <h3 class="text-xl font-bold mb-4 flex items-center">
                    <i class="fa fa-bell text-primary mr-2"></i>
                    最近动态
                </h3>
                <div class="space-y-4">
                    <div class="flex items-start p-3 bg-purple-50 rounded-lg hover:bg-purple-100 transition-colors">
                        <div class="bg-primary p-2 rounded-full mr-4">
                            <i class="fa fa-check-circle text-white"></i>
                        </div>
                        <div class="flex-grow">
                            <p class="font-semibold text-dark">作业评分完成</p>
                            <p class="text-sm text-gray-600">《数据结构-第三章》已完成评分，平均分：85.5分</p>
                            <p class="text-xs text-gray-400 mt-1">5分钟前</p>
                        </div>
                    </div>

                    <div class="flex items-start p-3 bg-green-50 rounded-lg hover:bg-green-100 transition-colors">
                        <div class="bg-secondary p-2 rounded-full mr-4">
                            <i class="fa fa-file-upload text-white"></i>
                        </div>
                        <div class="flex-grow">
                            <p class="font-semibold text-dark">新作业提交</p>
                            <p class="text-sm text-gray-600">15名学生提交了《Python编程作业-Week4》</p>
                            <p class="text-xs text-gray-400 mt-1">30分钟前</p>
                        </div>
                    </div>

                    <div class="flex items-start p-3 bg-amber-50 rounded-lg hover:bg-amber-100 transition-colors">
                        <div class="bg-accent p-2 rounded-full mr-4">
                            <i class="fa fa-trophy text-white"></i>
                        </div>
                        <div class="flex-grow">
                            <p class="font-semibold text-dark">优秀作业推荐</p>
                            <p class="text-sm text-gray-600">张三的作业被评为本周优秀作业，得分：98分</p>
                            <p class="text-xs text-gray-400 mt-1">2小时前</p>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <!-- 页脚 -->
        <footer class="bg-white border-t mt-8 py-6">
            <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
                <p>© 2025 AI作业评分系统 版权所有 | 让教育更智能，让评分更公正</p>
            </div>
        </footer>
    </div>

    <!-- Agent对话部分 -->
    <div class="fixed bottom-8 right-8 z-50">
        <!-- 对话窗口 -->
        <div id="chatContainer" class="chat-container fixed bottom-8 right-8 w-80 md:w-96 bg-white rounded-xl chat-shadow h-[500px] flex flex-col">
            <!-- 对话窗口头部 -->
            <div class="bg-gradient-to-r from-purple-600 to-blue-600 text-white p-4 rounded-t-xl flex justify-between items-center">
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center">
                        <i class="fa fa-graduation-cap text-white"></i>
                    </div>
                    <div>
                        <h3 class="font-bold">AI评分助手</h3>
                        <p class="text-xs text-white/80">随时为您解答</p>
                    </div>
                </div>
                <button id="closeChat" class="text-white hover:text-gray-200 transition-colors">
                    <i class="fa fa-times"></i>
                </button>
            </div>

            <!-- 对话内容区域 -->
            <div id="chatMessages" class="flex-grow p-4 overflow-y-auto space-y-4">
                <div class="flex items-start">
                    <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center mr-2 flex-shrink-0">
                        <i class="fa fa-graduation-cap text-primary text-sm"></i>
                    </div>
                    <div class="message-bubble bg-primary/5 p-3 rounded-lg rounded-tl-none">
                        <p>你好！我是AI评分助手 🎓</p>
                        <p class="text-sm mt-1">我可以帮助你：</p>
                        <ul class="text-sm mt-2 space-y-1">
                            <li>• 了解作业提交流程</li>
                            <li>• 查询评分标准</li>
                            <li>• 获取学习建议</li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- 输入区域 -->
            <div class="border-t p-3 bg-gray-50">
                <form id="chatForm" class="flex space-x-2">
                    <input type="text" id="userInput" placeholder="询问作业评分、提交等问题..." 
                           class="flex-grow px-4 py-2 border border-gray-200 rounded-full focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary bg-white">
                    <button type="submit" class="bg-gradient-to-r from-purple-600 to-blue-600 text-white w-10 h-10 rounded-full flex items-center justify-center hover:opacity-90 transition-all shadow-md">
                        <i class="far fa-paper-plane"></i>
                    </button>
                </form>
            </div>
        </div>

        <!-- 悬浮头像按钮 -->
        <button id="openChatBtn" class="agent-avatar bg-gradient-to-r from-purple-600 to-blue-600 text-white w-16 h-16 rounded-full shadow-xl flex items-center justify-center hover:shadow-2xl">
            <i class="fa fa-graduation-cap text-2xl"></i>
        </button>
    </div>

    <script>
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            const chatContainer = document.getElementById('chatContainer');
            const openChatBtn = document.getElementById('openChatBtn');
            const closeChatBtn = document.getElementById('closeChat');
            const chatForm = document.getElementById('chatForm');
            const userInput = document.getElementById('userInput');
            const chatMessages = document.getElementById('chatMessages');

            // 存储当前对话ID
            let conversationId = localStorage.getItem('agentConversationId');
            if (!conversationId) {
                conversationId = '{{ conversation_id }}';
                localStorage.setItem('agentConversationId', conversationId);
            }

            // 打开对话窗口
            openChatBtn.addEventListener('click', function() {
                chatContainer.classList.add('active');
                openChatBtn.classList.add('hidden');
            });

            // 关闭对话窗口
            closeChatBtn.addEventListener('click', function() {
                chatContainer.classList.remove('active');
                openChatBtn.classList.remove('hidden');
            });

            // 提交消息
            chatForm.addEventListener('submit', function(e) {
                e.preventDefault();
                const message = userInput.value.trim();
                if (message) {
                    // 添加用户消息到界面
                    addMessageToUI('user', message);

                    // 清空输入框
                    userInput.value = '';

                    // 发送消息到后端
                    sendMessageToAgent(message);
                }
            });

            // 添加消息到界面
            function addMessageToUI(sender, content) {
                const messageDiv = document.createElement('div');
                messageDiv.className = `flex items-start ${sender === 'user' ? 'justify-end' : ''}`;

                if (sender === 'user') {
                    messageDiv.innerHTML = `
                        <div class="message-bubble bg-primary text-white p-3 rounded-lg rounded-tr-none">
                            <p>${content}</p>
                        </div>
                    `;
                } else {
                    messageDiv.innerHTML = `
                        <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center mr-2 flex-shrink-0">
                            <i class="fa fa-graduation-cap text-primary text-sm"></i>
                        </div>
                        <div class="message-bubble bg-primary/5 p-3 rounded-lg rounded-tl-none">
                            <p>${content}</p>
                        </div>
                    `;
                }

                chatMessages.appendChild(messageDiv);
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }

            // 发送消息到Agent
            function sendMessageToAgent(message) {
                // 显示"正在输入"状态
                const typingDiv = document.createElement('div');
                typingDiv.id = 'typingIndicator';
                typingDiv.className = 'flex items-start';
                typingDiv.innerHTML = `
                    <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center mr-2 flex-shrink-0">
                        <i class="fa fa-graduation-cap text-primary text-sm"></i>
                    </div>
                    <div class="message-bubble bg-primary/5 p-3 rounded-lg rounded-tl-none">
                        <p class="text-gray-500">AI正在分析中...</p>
                    </div>
                `;
                chatMessages.appendChild(typingDiv);
                chatMessages.scrollTop = chatMessages.scrollHeight;

                // 发送请求到后端
                fetch('/api/agent', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message: message,
                        conversation_id: conversationId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    // 移除"正在输入"状态
                    document.getElementById('typingIndicator').remove();

                    // 添加Agent回复到界面
                    addMessageToUI('agent', data.response);
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('typingIndicator').remove();
                    addMessageToUI('agent', '抱歉，AI助手暂时无法响应，请稍后再试或联系管理员。');
                });
            }
        });
    </script>
</body>
</html>
    ''', conversation_id=str(uuid.uuid4()))


# 处理Agent请求的API
@app.route('/api/agent', methods=['POST'])
def agent_api():
    data = request.json
    message = data.get('message', '')
    conversation_id = data.get('conversation_id', '')

    if not conversation_id:
        conversation_id = str(uuid.uuid4())

    # 调用Agent获取响应
    response = call_agent(message, conversation_id)

    # 存储对话历史（实际项目中可使用数据库）
    if conversation_id not in conversations:
        conversations[conversation_id] = []
    conversations[conversation_id].append({
        'role': 'user',
        'content': message
    })
    conversations[conversation_id].append({
        'role': 'agent',
        'content': response
    })

    return jsonify({
        'response': response,
        'conversation_id': conversation_id
    })


if __name__ == '__main__':
    app.run(host="0.0.0.0",debug=True,port=8082)